<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\room;


use app\adminapi\service\DataHandleService;
use app\common\model\room\RoomHospital;
use app\common\logic\BaseLogic;
use app\common\model\room\RoomHospitalDevice;
use app\common\model\room\RoomHospitalUser;
use app\common\model\user\User;
use app\common\service\ConfigService;
use think\facade\Config;
use think\facade\Db;


/**
 * 全院房间管理逻辑
 * Class RoomHospitalLogic
 * @package app\adminapi\logic\room
 */
class RoomHospitalLogic extends BaseLogic {


    /**
     * @notes 添加全院房间管理
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function add(array $params): bool {
        $passwordSalt = Config::get('project.unique_identification');
        $password = create_password("123456", $passwordSalt);
        $avatar = ConfigService::get('default_image', 'user_avatar');
        $user_ids = [];
        $params['user_name'] = $params['user'][0]['user_name'] ?? '';
        $params['user_mobile'] = $params['user'][0]['user_mobile'] ?? '';
        $params['user_id'] = $params['user'][0]['user_id'] ?? 0;
        foreach ($params['user'] as $k => $v) {
            if (empty($v['user_name'])) {
                $user_ids[] = 0;
                $params['user'][$k]['user_id'] = 0;
                $params['user_id'] = 0; // foreach 外面读取不到
                continue;
            }

            $user = User::where([
                "cid" => $params['cid'],
                "real_name" => trim($v['user_name']),
                "mobile" => trim($v['user_mobile']),
            ])->find();

            if ($user) {
                $user_id = $user['id'];
            } else {
                $sn = User::createUserSn();
                // ID返回无效
//                $user_id = User::create([
//                    "cid" => $params['cid'],
//                    "did" => 0,
//                    "real_name" => trim($v['user_name']),
//                    "mobile" => trim($v['user_mobile']),
//                    "nickname" => trim($v['user_name']),
//                    "sn" => $sn,
//                    "account" => $sn,
//                    "password" => $password,
//                    "avatar" => $avatar,
//                    "channel" => 4,
//                    "create_time" => time(),
//                    "update_time" => time(),
//                ])->getLastInsID();
                $user_id = Db::name("user")->insertGetId([
                    "cid" => $params['cid'],
                    "did" => 0,
                    "real_name" => trim($v['user_name']),
                    "mobile" => trim($v['user_mobile']),
                    "nickname" => trim($v['user_name']),
                    "sn" => $sn,
                    "account" => $sn,
                    "password" => $password,
                    "avatar" => $avatar,
                    "channel" => 4,
                    "create_time" => time(),
                    "update_time" => time(),
                ]);
            }

            $user_ids[] = $user_id ?? 0;
            $params['user'][$k]['user_id'] = $user_id ?? 0;
            // foreach 外面读取不到
            $params['user_id'] = $params['user'][0]['user_id'] ?? 0;
        }

        Db::startTrans();
        try {
            $create = [
                'cid' => $params['cid'],
                'bid' => $params['bid'],
                'name' => $params['name'],
                'status' => $params['status'],
                'type' => $params['type'],
                'add_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s"),
                'device_total' => $params['device_total'],
                'device_fee_time' => $params['device_fee_time'] ?? null,
                'sort' => $params['sort'] ?? 10000,

                'room_department' => trim($params['room_department']),
                'room_department_sort' => DataHandleService::getStringFirstKeySort(trim($params['room_department'])),
                'address' => $params['address'] ?? null,
                'lift_type' => $params['lift_type'],
                'lift_fee' => $params['lift_fee'] ?? 0,
                'second_pressure_fee' => $params['second_pressure_fee'] ?? 0,

                'user_id' => $params['user_id'] ?? 0,
                'user_name' => trim($params['user_name']),
                'user_mobile' => trim($params['user_mobile']),
            ];
            $rid = RoomHospital::create($create)->getLastInsID();

            // $sdc = ConfigService::get('room_apartment', 's_device_coefficient');
            // $sdp = ConfigService::get('room_apartment', 's_device_price');
            $ddc = ConfigService::get('room_apartment', 'd_device_coefficient');
            $ddp = ConfigService::get('room_apartment', 'd_device_price');

            $device_create = [
                "cid" => $params['cid'],
                "bid" => $params['bid'] ?? 0,
                "sort" => $create['sort'],
                "rid" => $rid,
                'add_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s"),
                "status" => 1,
                "room_master" => 1, // 主房间
                "device_type" => 2, // 默认电表
                "coefficient" => $ddc, // 系数
                "price" => $ddp, // 水电价
            ];
            RoomHospitalDevice::create($device_create);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑全院房间管理
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function edit(array $params): bool {
        $passwordSalt = Config::get('project.unique_identification');
        $password = create_password("123456", $passwordSalt);
        $avatar = ConfigService::get('default_image', 'user_avatar');
        $user_ids = [];
        $params['user_name'] = $params['user'][0]['user_name'] ?? '';
        $params['user_mobile'] = $params['user'][0]['user_mobile'] ?? '';
        $params['user_id'] = $params['user'][0]['user_id'] ?? 0;
        foreach ($params['user'] as $k => $v) {
            if (empty($v['user_name'])) {
                $user_ids[] = 0;
                $params['user'][$k]['user_id'] = 0;
                $params['user_id'] = 0; // foreach 外面读取不到
                continue;
            }

            $user = User::where([
                "cid" => $params['cid'],
                "real_name" => trim($v['user_name']),
                "mobile" => trim($v['user_mobile']),
            ])->find();

            if ($user) {
                $user_id = $user['id'];
            } else {
                $sn = User::createUserSn();
                $user_id = Db::name("user")->insertGetId([
                    "cid" => $params['cid'],
                    "did" => 0,
                    "real_name" => trim($v['user_name']),
                    "mobile" => trim($v['user_mobile']),
                    "nickname" => trim($v['user_name']),
                    "sn" => $sn,
                    "account" => $sn,
                    "password" => $password,
                    "avatar" => $avatar,
                    "channel" => 4,
                    "create_time" => time(),
                    "update_time" => time(),
                ]);
//                $user_id = User::create([
//                    "cid" => $params['cid'],
//                    "did" => 0,
//                    "real_name" => trim($v['user_name']),
//                    "mobile" => trim($v['user_mobile']),
//                    "nickname" => trim($v['user_name']),
//                    "sn" => $sn,
//                    "account" => $sn,
//                    "password" => $password,
//                    "avatar" => $avatar,
//                    "channel" => 4,
//                    "create_time" => time(),
//                    "update_time" => time(),
//                ])->getLastInsID();
            }

            $user_ids[] = $user_id ?? 0;
            $params['user'][$k]['user_id'] = $user_id ?? 0;
            // foreach 外面读取不到
            $params['user_id'] = $params['user'][0]['user_id'] ?? 0;
        }

        Db::startTrans();
        try {
            $update = [
                'cid' => $params['cid'],
                'bid' => $params['bid'],
                'name' => $params['name'],
                'status' => $params['status'],
                'type' => $params['type'],
                'update_time' => date("Y-m-d H:i:s"),
                'device_total' => $params['device_total'],
                'device_fee_time' => $params['device_fee_time'],
                'sort' => $params['sort'],

                'room_department' => trim($params['room_department']),
                'room_department_sort' => DataHandleService::getStringFirstKeySort(trim($params['room_department'])),
                'address' => $params['address'],
                'lift_type' => $params['lift_type'],
                'lift_fee' => $params['lift_fee'],
                'second_pressure_fee' => $params['second_pressure_fee'],

                'user_id' => $params['user_id'],
                'user_name' => trim($params['user_name']),
                'user_mobile' => trim($params['user_mobile']),
            ];
            RoomHospital::where('id', $params['id'])->update($update);

            $device_update = [
                'cid' => $update['cid'],
                'bid' => $update['bid'],
                'update_time' => date("Y-m-d H:i:s"),
                'sort' => $update['sort'],
            ];
            RoomHospitalDevice::where('rid', $params['id'])->update($device_update);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除全院房间管理
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function delete(array $params): bool {
        RoomHospitalDevice::whereIn("rid", $params['id'])->delete();
        return RoomHospital::destroy($params['id']);
    }


    /**
     * @notes 获取全院房间管理详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function detail($params): array {
        return RoomHospital::findOrEmpty($params['id'])->toArray();
    }

}
